package core.cards.election.model;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import core.cards.CardResultBackend;
import core.cards.IFormBackend;

public class ElectionResultBackend extends CardResultBackend {
	private ElectionBackend votingCard;
	
	private ElectionResultSubBackend generalSubBackend;
	private Map<String, ElectionResultSubBackend> locatorUriToSubBackendMap;
	private List<ElectionResultSubBackend> subBackendList;
	
	public ElectionResultBackend(ElectionBackend votingCard) {
		this.votingCard = votingCard;
		
		generalSubBackend = new ElectionResultSubBackend("General", votingCard);
		locatorUriToSubBackendMap = new HashMap<String, ElectionResultSubBackend>();
		subBackendList = new ArrayList<ElectionResultSubBackend>();
		subBackendList.add(generalSubBackend);
	}
	
	public void setMaxVotersCount(int maxVotersCount) {
		generalSubBackend.setMaxVotersCount(maxVotersCount);
	}
	
	public void addRkw(String locatorUri, String rkwName, int maxVotersCount) {
		ElectionResultSubBackend newSubBackend = new ElectionResultSubBackend(rkwName, votingCard);
		newSubBackend.setMaxVotersCount(maxVotersCount);
		if(locatorUriToSubBackendMap.get(locatorUri) != null) {
			subBackendList.remove(locatorUriToSubBackendMap.get(locatorUri));
		}
		locatorUriToSubBackendMap.put(locatorUri, newSubBackend);
		subBackendList.add(newSubBackend);
	}
	
	@Override
	protected void addVoteToGeneral(IFormBackend vote) {
		generalSubBackend.addVote((ElectionBackend)vote);
	}

	@Override
	protected void addVoteToRkw(IFormBackend vote, String locatorUri) {
		if(locatorUriToSubBackendMap.get(locatorUri) != null) {
			locatorUriToSubBackendMap.get(locatorUri).addVote((ElectionBackend)vote);
		}
	}
	
	@Override
	protected void increaseVotersCountForGeneral(int votersCount) {
		generalSubBackend.increaseVotersCount(votersCount);
	}

	@Override
	protected void increaseVotersCountForRkw(int votersCount, String locatorUri) {
		if(locatorUriToSubBackendMap.get(locatorUri) != null) {
			locatorUriToSubBackendMap.get(locatorUri).increaseVotersCount(votersCount);
		}
	}

	@Override
	public String toString() {
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append(generalSubBackend);
		for(ElectionResultSubBackend electionResultSubBackend : subBackendList) {
			stringBuilder.append(electionResultSubBackend);
		}
		return stringBuilder.toString();
	}

	public ElectionResultSubBackend getGeneralElectionResultSubBackend() {
		return generalSubBackend;
	}
	
	public List<ElectionResultSubBackend> getElectionResultSubBackendList() {
		return subBackendList;
	}
}
